"""
系统监控服务
创建时间：2025-09-17
作者：开发团队
目的：处理系统状态监控相关业务逻辑
"""

import psutil
import platform
from sqlalchemy.orm import Session
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy import text
from datetime import datetime, timezone
from ..utils.logger import get_logger

# 获取日志记录器
logger = get_logger(__name__)


def get_system_status() -> dict[str, object]:
    """
    获取系统状态信息
    :return: 系统状态信息
    """
    try:
        # 获取CPU使用率
        cpu_percent = psutil.cpu_percent(interval=1)
        
        # 获取内存信息
        memory = psutil.virtual_memory()
        memory_percent = memory.percent
        
        # 获取磁盘信息
        disk = psutil.disk_usage('/')
        disk_percent = (disk.used / disk.total) * 100 if disk.total > 0 else 0
        
        # 获取系统启动时间
        boot_time = datetime.fromtimestamp(psutil.boot_time())
        uptime = datetime.now() - boot_time
        
        return {
            "server": {
                "cpu_usage": round(cpu_percent, 2),
                "memory_usage": round(memory_percent, 2),
                "disk_usage": round(disk_percent, 2),
                "uptime": int(uptime.total_seconds()),
                "os": platform.system(),
                "platform": platform.platform()
            },
            "database": {
                "status": "connected",  # 实际项目中应检查数据库连接状态
                "connections": 0,  # 实际项目中应获取实际连接数
                "size": 0  # 实际项目中应获取数据库大小
            },
            "services": []  # 实际项目中应检查各服务状态
        }
    except Exception as e:
        logger.error(f"获取系统状态异常: {str(e)}")
        return {
            "server": {
                "cpu_usage": 0,
                "memory_usage": 0,
                "disk_usage": 0,
                "uptime": 0,
                "os": platform.system(),
                "platform": platform.platform()
            },
            "database": {
                "status": "error",
                "connections": 0,
                "size": 0
            },
            "services": []
        }


def get_database_status(db: Session) -> dict[str, object]:
    """
    获取数据库状态信息
    :param db: 数据库会话
    :return: 数据库状态信息
    """
    try:
        # 执行简单的查询来检查数据库连接
        db.execute(text("SELECT 1"))
        
        # 获取数据库统计信息（示例）
        # 在实际项目中，这里应该查询数据库的实际统计信息
        table_count = 0
        try:
            # 获取表数量
            result = db.execute(text("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = DATABASE()"))
            table_count = result.scalar() or 0
        except:
            pass
        
        return {
            "status": "connected",
            "connections": 0,  # 实际项目中应获取实际连接数
            "size": 0,  # 实际项目中应获取数据库大小
            "tables": table_count
        }
    except SQLAlchemyError as e:
        logger.error(f"数据库状态检查失败: {str(e)}")
        return {
            "status": "disconnected",
            "connections": 0,
            "size": 0,
            "error": str(e)
        }
    except Exception as e:
        logger.error(f"获取数据库状态异常: {str(e)}")
        return {
            "status": "error",
            "connections": 0,
            "size": 0,
            "error": str(e)
        }


def get_service_status() -> list[dict[str, object]]:
    """
    获取服务状态信息
    :return: 服务状态列表
    """
    # 实际项目中应检查各服务的实际状态
    # 这里返回示例数据
    return [
        {
            "name": "auth_service",
            "status": "running",
            "last_check": datetime.now(timezone.utc).isoformat()
        },
        {
            "name": "data_service",
            "status": "running",
            "last_check": datetime.now(timezone.utc).isoformat()
        },
        {
            "name": "notification_service",
            "status": "running",
            "last_check": datetime.now(timezone.utc).isoformat()
        }
    ]